package com.yulinlin.websocket.node;


import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yulinlin.websocket.node.consume.RedisConsumer;
import com.yulinlin.websocket.node.consume.TopicConsumer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.util.List;

@EnableDiscoveryClient
@SpringBootApplication
@Slf4j
public class WebSocketNodeApplication implements CommandLineRunner {

	@Value("${socketio.port}")
	private int  port ;

	@Bean
	public Configuration configuration() {
		Configuration config = new Configuration();
		config.setHostname("localhost");
		config.setPort(port);
		return config;
	}

		/**
         * netty-socketio服务器
         */
	@Bean
	public SocketIOServer socketIOServer() {


		SocketIOServer server = new SocketIOServer(configuration());

		server.startAsync();



		Runtime.getRuntime().addShutdownHook(new Thread(()  -> {
			server.stop();
		}));

		return server;
	}

	/**
	 * 用于扫描netty-socketio的注解，比如 @OnConnect、@OnEvent
	 */
	@Bean
	public SpringAnnotationScanner springAnnotationScanner() {
		return new SpringAnnotationScanner(socketIOServer());
	}



	@Bean
	public RedisMessageListenerContainer redisMessageListenerContainer(
			RedisConnectionFactory connectionFactory,
			List<RedisConsumer> consumerList,
			RedisSerializer redisSerializer
	)
	{

		RedisMessageListenerContainer container = new RedisMessageListenerContainer();
		container.setConnectionFactory(connectionFactory);
		//订阅多个频道

		for (RedisConsumer consumer : consumerList) {

			container.addMessageListener(consumer,new PatternTopic(consumer.getChannel()));
		}
		container.setTopicSerializer(redisSerializer);

		container.afterPropertiesSet();
		return container;
	}

	@Override
	public void run(String... args) throws Exception {

	}

	public static void main(String[] args) {

		SpringApplication.run(WebSocketNodeApplication.class, args);
	}

}
